<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\NewArrivalRequest;
use App\Models\V1\Clothes;
use App\Models\V1\ClotheSize;
use App\Models\V1\DailyUse;
use App\Models\V1\Major;
use App\Models\V1\NewArrival;
use App\Models\V1\Pays;
use App\Models\V1\ReportProcess;
use App\Models\V1\Term;
use App\Models\V1\Textbook;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;

class NewArrivalsController extends Controller
{
    //
    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $years = $this->getEnrollmentYears();
        $data['years'] = $years;
        return view('v1.newData.new_arrival',$data);
    }

    /**
     * 获取迎新换届数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的班级数据
        $data = $this->getNewArrivalList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['enrollment_year'] = $item['enrollment_year'];
                    $formatItem['enrollment_term'] = $item['enrollment_term'];
                    $formatItem['enrollment_serial'] = $item['enrollment_serial'];
                    $formatItem['isOn'] = $this->formateIsShowData($item['isOn']);
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $loginUser = Auth::user();
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                $now_year = Carbon::now()->year;
                $last_year = $now_year - 1;
                $next_year = $now_year + 1;
                $data['years'] = [
                    $last_year,
                    $now_year,
                    $next_year
                ];
                $data['terms'] = $this->getTermList();
                $data['processes'] = $this->getProcessList();
                return view('v1.form.new_arrival_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $currentArrival = $this->getNewArrivalByCode($code);
                $currentArrival['isOn'] = $this->formatIsShowItemData($currentArrival['isOn']);
                $data['itemData'] = $currentArrival;
                return view('v1.form.new_arrival_item', $data);
                break;
        }
    }

    /**
     * 显示迎新换届数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新换届[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required|unique:basic_new_arrivals';
            $rules['enrollment_year'] = 'bail|required';
            $rules['enrollment_term'] = 'bail|required';
            $rules['enrollment_serial'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '迎新代码不能为空';
            $messages['code.unique'] = '迎新代码已存在';
            $messages['enrollment_year.required'] = '招生年份不能为空';
            $messages['enrollment_term.required'] = '招生学期不能为空';
            $messages['enrollment_serial.required'] = '招生序号不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '迎新换届[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除班级基本信息
     *
     * @param NewArrivalRequest $request
     * @return array
     */
    public function deleteData(NewArrivalRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新换届代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateNewArrival($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '迎新换届代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除班级基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新换届批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '班级批量删除成功！';
            }
        }

        return $response;
    }


    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $contentJson['content'] = $request->input('content');
        $first = NewArrival::where('isOn',true)->first();
        $old_arrival_code='';
        if (!empty($first) || isset($first)) {
            $old_arrival_code = $first->code;
            $updateData = [
                'isOn' => false,
            ];
            $rspObj = $first->update($updateData);
        }
        $arrival_code = $request->input('code');
        // 拼装新增数据数组
        $insertData = [
            'code' => $arrival_code,
            'enrollment_year' => strval($request->input('enrollment_year')),
            'enrollment_term' => $request->input('enrollment_term'),
            'enrollment_serial' => $request->input('enrollment_serial'),
            'isOn' => true,
        ];
        $rspObj = NewArrival::create($insertData);
        //处理数据复用
        if (strlen($old_arrival_code) > 0) {
            $process_codes = ['process1','process2','process3','process4','process5','process6'];
            for ($i=0;$i<count($process_codes);$i++) {
                $item = $process_codes[$i];
                $value = $request->input($item);
                if ($value === 'on') {  //
                    $this->copyData($i,$old_arrival_code,$arrival_code);
                }
            }
        }
        return $rspObj;
    }


    private function copyData($i,$old_arrival_code,$arrival_code) {
        switch ($i){
            case 0:
                $this->insertDailyUseData($old_arrival_code,$arrival_code);
                break;
            case 1:
                $this->insertTextbookData($old_arrival_code,$arrival_code);
                break;
            case 2:
                $this->insertPayData($old_arrival_code,$arrival_code);
                break;
            case 3:
                $this->insertReportProcessData($old_arrival_code,$arrival_code);
                break;
            case 4:
                $this->insertClothData($old_arrival_code,$arrival_code);
                break;
            case 5:
                $this->insertMajorData($old_arrival_code,$arrival_code);
                break;
            default:
                break;
        }
    }

    //生活用品数据
    private function insertDailyUseData($old_arrival_code,$arrival_code) {
        Log::info('insertDailyUseData');
        $datas = DailyUse::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'remark'=>$item->remark,
                'count'=>$item->count,
                'unit'=>$item->unit,
                'sex_limit'=>$item->sex_limit,
                'arrival_code'=>$arrival_code,
            ];
            DailyUse::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    //教材数据
    private function insertTextbookData($old_arrival_code,$arrival_code) {
        Log::info('insertTextbookData');
        $datas = Textbook::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'remark'=>$item->remark,
                'count'=>$item->count,
                'unit'=>$item->unit,
                'majors'=>$item->majors,
                'arrival_code'=>$arrival_code,
            ];
            Textbook::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    //费用数据
    private function insertPayData($old_arrival_code,$arrival_code) {
        Log::info('insertPayData');
        $datas = Pays::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'remark'=>$item->remark,
                'amount'=>$item->amount,
                'unit'=>$item->unit,
                'type'=>$item->type,
                'sub_amount'=>$item->sub_amount,
                'arrival_code'=>$arrival_code,
            ];
            Pays::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    //报到流程数据
    private function insertReportProcessData($old_arrival_code,$arrival_code) {
        Log::info('insertReportProcessData');
        $datas = ReportProcess::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'detail'=>$item->detail,
                'address'=>$item->address,
                'reception_person'=>$item->reception_person,
                'handle_procedures'=>$item->handle_procedures,
                'remark'=>$item->remark,
                'relate_information'=>$item->relate_information,
                'arrival_code'=>$arrival_code,
            ];
            ReportProcess::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    //志校服据insertClothData
    private function insertClothData($old_arrival_code,$arrival_code) {
        Log::info('insertClothData');
        $datas = Clothes::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'picture'=>$item->picture,
                'remark'=>$item->remark,
                'count'=>$item->count,
                'unit'=>$item->unit,
                'sex_limit'=>$item->sex_limit,
                'arrival_code'=>$arrival_code,
            ];
            Clothes::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }

        $datas = ClotheSize::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'cloth_code'=>$item->cloth_code,
                'height_low'=>$item->height_low,
                'height_high'=>$item->height_high,
                'size'=>$item->size,
                'cloth_length'=>$item->cloth_length,
                'bust'=>$item->bust,
                'arrival_code'=>$arrival_code,
            ];
            ClotheSize::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    //志愿数据
    private function insertMajorData($old_arrival_code,$arrival_code) {
        Log::info('insertMajorData');
        $datas = Major::where('arrival_code',$old_arrival_code)->get();
        foreach ($datas as $item) {
            $insert_data = [
                'code'=>$item->code,
                'name'=>$item->name,
                'min_number'=>$item->min_number,
                'max_number'=>$item->max_number,
                'count'=>$item->count,
                'parent_code'=>$item->parent_code,
                'arrival_code'=>$arrival_code,
            ];
            Major::updateOrCreate(['code'=>$item->code,'arrival_code'=>$arrival_code],$insert_data);
        }
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getNewArrivalList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = NewArrival::orderBy('created_at', 'desc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = NewArrival::where('enrollment_year', 'like', '%' . $keywords . '%')->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    private function getNewArrivalByCode($code)
    {
        $arrival = NewArrival::where('code', $code)->first();
        return $arrival;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentYears()
    {
        $years = NewArrival::all()->pluck('enrollment_year')->unique()->toArray();
        return $years;
    }

    /***
     * 获取所有学期
     */
    private function getTermList() {
        $terms = Term::all('code','name')->toArray();
        return $terms;
    }

    private function getProcessList() {
        $process_codes = ['process1','process2','process3','process4','process5','process6'];
        $process_names = ['生活用品','新生教材','费用类别','报到流程','校服清单','志愿设置'];
        $formatProcess = array();
        for ($i = 0; $i < count($process_codes); $i++ ) {
            $process = [
                'code' => $process_codes[$i],
                'name' => $process_names[$i],
            ];
            array_push($formatProcess,$process);
        }
        return $formatProcess;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateNewArrival(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = NewArrival::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = NewArrival::where('code', $where)->delete();
        }

        return $rspObj;
    }

    /**
     * 格式化显示发布信息
     *
     * @param $val
     * @return string
     */
    private function formateIsShowData($val)
    {
        $strFormat = '<span class="layui-bg-gray">否</span>';
        if ($val) {
            $strFormat = '<span class="layui-bg-green">是</span>';
        }
        return $strFormat;
    }

    private function formatIsShowItemData($val)
    {
        $strFormat = '否';
        if ($val) {
            $strFormat = '是';
        }
        return $strFormat;
    }

}
